using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return;
using RBAC.Write.Api.Infrastructure;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement.Return
{
    /// <summary>
    /// 删除退货通知单处理器
    /// </summary>
    public class DeleteReturnNoticeHandler : IRequestHandler<DeleteReturnNoticeCommand, APIResult<int>>
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbConnectionFactory">数据库连接工厂</param>
        public DeleteReturnNoticeHandler(IDbConnectionFactory dbConnectionFactory)
        {
            _dbConnectionFactory = dbConnectionFactory;
        }

        /// <summary>
        /// 处理删除退货通知单请求
        /// </summary>
        /// <param name="request">删除命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<int>> Handle(DeleteReturnNoticeCommand request, CancellationToken cancellationToken)
        {
            IDbConnection connection = null;
            IDbTransaction transaction = null;

            try
            {
                connection = _dbConnectionFactory.CreateConnection();
                transaction = connection.BeginTransaction();

                // 1. 检查退货通知单是否存在
                var sqlCheck = @"SELECT COUNT(1) FROM ReturnNotice WHERE Id = @Id AND IsDeleted = 0";
                var exists = await connection.ExecuteScalarAsync<int>(sqlCheck, new { request.Id }, transaction);

                if (exists == 0)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "退货通知单不存在"
                    };
                }

                // 2. 逻辑删除退货通知单主表
                var sqlDeleteMain = @"UPDATE ReturnNotice SET IsDeleted = 1, UpdateTime = GETDATE() WHERE Id = @Id";
                var affectedRows = await connection.ExecuteAsync(sqlDeleteMain, new { request.Id }, transaction);

                // 3. 逻辑删除退货物料明细表
                var sqlDeleteItems = @"UPDATE ReturnMaterials SET IsDeleted = 1, UpdateTime = GETDATE() WHERE ReturnNoticeId = @Id";
                await connection.ExecuteAsync(sqlDeleteItems, new { request.Id }, transaction);

                transaction.Commit();

                return new APIResult<int>
                {
                    Code = APIEnums.Success,
                    Msg = "删除成功",
                    Data = affectedRows
                };
            }
            catch (Exception ex)
            {
                transaction?.Rollback();
                return new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = $"删除失败：{ex.Message}"
                };
            }
            finally
            {
                transaction?.Dispose();
                connection?.Dispose();
            }
        }
    }
}